<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\store\controller\Controller;

class Identify extends Controller
{
    public $api_key = "q53U62f2llex17hipVjVlnve";
    public $secret_key = "1IacgQ2SKgdyYreBruwPMMmXaUQXnAFA";

    public $apis = [
        // 行驶证
        'vehicle_license' => 'https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_license',
        // 驾驶证
        'driving_license' => 'https://aip.baidubce.com/rest/2.0/ocr/v1/driving_license',
        // 道路运输证
        'road_transport_certificate' => 'https://aip.baidubce.com/rest/2.0/solution/v1/iocr/recognise',
        // 身份证
        'idcard' => 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard',

        // 通用文字识别
        'general_basic' => 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic',
    ];

    /**
     * 压缩图片
     * @param $source
     * @param $destination
     * @param $scale float 压缩比例
     * @param $quality
     * @return bool
     */
    public function compressImage($source, $destination, $scale, $quality)
    {
        $info = getimagesize($source);
        $width = $info[0];
        $height = $info[1];

        // 计算缩放后的宽度和高度
        $newWidth = $width;
        $newHeight = $height;

        // 创建缩略图
        $thumb = imagecreatetruecolor($newWidth, $newHeight);

        // 根据原图类型进行相应的处理
        if ($info['mime'] == 'image/jpeg') {
            $sourceImage = imagecreatefromjpeg($source);
        } elseif ($info['mime'] == 'image/png') {
            $sourceImage = imagecreatefrompng($source);
        } elseif ($info['mime'] == 'image/gif') {
            $sourceImage = imagecreatefromgif($source);
        } else {
            return false;
        }

        // 将原图复制到缩略图中
        imagecopyresampled($thumb, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

        $dlist = explode('/', $destination);
        array_pop($dlist);
        $this->mkdirs(implode('/', $dlist));
        // 保存缩略图
        if ($info['mime'] == 'image/jpeg') {
            imagejpeg($thumb, $destination, $quality);
        } elseif ($info['mime'] == 'image/png') {
            imagepng($thumb, $destination, 9);
        } elseif ($info['mime'] == 'image/gif') {
            imagegif($thumb, $destination);
        }

        return $destination;
    }

    //创建文件夹
    function mkdirs($dir, $mode = 0777)
    {
        if (is_dir($dir) || @mkdir($dir, $mode)) {
            return true;
        }
        if (!$this->mkdirs(dirname($dir), $mode)) {
            return false;
        }
        return @mkdir($dir, $mode);
    }

    /**
     * 获取图片的Base64编码(不支持url)
     * @date 2021-04-9 16:02:11
     *
     * @param $img_file string 传入本地图片地址
     *
     * @return string
     */
    public function imgToBase64($img_file)
    {

        $img_base64 = '';
        if (file_exists($img_file)) {
            $app_img_file = $img_file; // 图片路径
            $img_info = getimagesize($app_img_file); // 取得图片的大小，类型等
            $fp = fopen($app_img_file, "r"); // 图片是否可读权限
            if ($fp) {
                $filesize = filesize($app_img_file);
                $content = fread($fp, $filesize);
                $file_content = chunk_split(base64_encode($content)); // base64编码
                switch ($img_info[2]) {           //判读图片类型
                    case 1:
                        $img_type = "gif";
                        break;
                    case 2:
                        $img_type = "jpg";
                        break;
                    case 3:
                        $img_type = "png";
                        break;
                }
                $img_base64 = $file_content;//合成图片的base64编码
            }
            fclose($fp);
        }
        return $img_base64; //返回图片的base64
    }

    /**
     * 获取行驶证信息
     * @return array
     */
    public function getVehicleLicenseInfo($url)
    {
        $sourceImage = 'uploads/' . $url;
        $destinationImage = 'compress/' . $url;
        $scale = 0.5;
        $quality = 75;
        $url = $this->compressImage($sourceImage, $destinationImage, $scale, $quality);
        $image = $this->imgToBase64($url);


        $postData = [
            'image' => $image,
            'detect_direction' => 'false',
            'vehicle_license_side' => 'front',
            'unified' => 'false',
            'quality_warn' => 'false',
            'risk_warn' => 'false',
        ];
        $frontData = $this->run('vehicle_license', $postData);
        if (!empty($frontData['error_code'])) {
            return $this->renderError('getFront：' . $frontData['error_msg']);
        }
        $postData = [
            'image' => $image,
            'detect_direction' => 'false',
            'vehicle_license_side' => 'back',
            'unified' => 'false',
            'quality_warn' => 'false',
            'risk_warn' => 'false',
        ];
        $backData = $this->run('vehicle_license', $postData);
        if (!empty($backData['error_code'])) {
            return $this->renderError('getBack：' . $backData['error_msg']);
        }
        return $this->renderSuccess(array_merge($frontData['words_result'], $backData['words_result']));
    }

    /**
     * 获取道路运输证信息
     * @return array
     */
    public function getRoadTransportLicenseInfo($url)
    {
//        $sourceImage = 'uploads/' . $url;
//        $destinationImage = 'compress/' . $url;
//        $scale = 0.5;
//        $quality = 75;
//        $url = $this->compressImage($sourceImage, $destinationImage, $scale, $quality);
//        $image = $this->imgToBase64($url);
        $postData = [
            'url' => $url,
            'templateSign' => '6a37e3db58ba134c624775ef94592ee0'
        ];
        $data = $this->run('road_transport_certificate', $postData);
        if (!empty($data['error_code'])) {
            return $this->renderError($data['error_msg']);
        }
        $newData = [];
        foreach ($data['data']['ret'] as $item) {
            $newData[$item['word_name']] = $item['word'];
        }
        return $this->renderSuccess($newData);
    }

    /**
     * 获取文件base64编码
     * @param string $path 文件路径
     * @return string base64编码信息，不带文件头
     */
    private function getFileContentAsBase64($path)
    {
        return urlencode(base64_encode(file_get_contents($path)));
    }


    /**
     * 获取身份证信息
     * @return array
     */
    public function getIdcardInfo($url)
    {
        $sourceImage = 'uploads/' . $url;
        $destinationImage = 'compress/' . $url;
        $scale = 0.5;
        $quality = 75;
        $url = $this->compressImage($sourceImage, $destinationImage, $scale, $quality);
        $image = $this->imgToBase64($url);
        $postData = [
            'image' => $image,
            'id_card_side' => 'front',
        ];
        $data = $this->run('idcard', $postData);
        if (!empty($data['error_code'])) {
            return $this->renderError($data['error_msg']);
        }
        return $this->renderSuccess($data['words_result']);
    }

    /**
     * 通用文字识别
     * @return array
     */
    public function generalBasic($url)
    {
        $postData = [
            'url' => $url,
        ];
        $data = $this->run('general_basic', $postData);
        if (!empty($data['error_code'])) {
            return $this->renderError($data['error_msg']);
        }
        return $this->renderSuccess($data['words_result']);
    }


    /**
     * 获取驾驶证信息
     * @return array
     */
    public function getDrivingLicenseInfo($url)
    {
        $sourceImage = 'uploads/' . $url;
        $destinationImage = 'compress/' . $url;
        $scale = 0.5;
        $quality = 75;
        $url = $this->compressImage($sourceImage, $destinationImage, $scale, $quality);
        $image = $this->imgToBase64($url);
        $postData = [
            'image' => $image,
        ];
        $data = $this->run('driving_license', $postData);
        if (!empty($data['error_code'])) {
            return $this->renderError($data['error_msg']);
        }
        return $this->renderSuccess($data['words_result']);
    }

    /**
     * 发送数据
     * @return array
     */
    private function run($apikey, $postData)
    {
        $api = $this->apis[$apikey];
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "{$api}?access_token={$this->getAccessToken()}",
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_CUSTOMREQUEST => 'POST',

            CURLOPT_POSTFIELDS => http_build_query($postData),

            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/x-www-form-urlencoded',
                'Accept: application/json'
            ),

        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return json_decode($response, true);
    }

    /**
     * 使用 AK，SK 生成鉴权签名（Access Token）
     * @return string 鉴权签名信息（Access Token）
     */
    private function getAccessToken()
    {
        $curl = curl_init();
        $postData = array(
            'grant_type' => 'client_credentials',
            'client_id' => $this->api_key,
            'client_secret' => $this->secret_key
        );
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://aip.baidubce.com/oauth/2.0/token',
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => http_build_query($postData)
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $rtn = json_decode($response);
        return $rtn->access_token;
    }
}
